package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.excel.SupplyExcelDto;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.*;
import com.yunyao.common.dto.SoSupplyDto;

import com.yunyao.dao.service.bamu.IBamuAuditConfirmHistoryService;
import com.yunyao.dao.service.bamu.IBamuPurchaseApplyService;
import com.yunyao.dao.service.bamu.IBamuSoSupplyService;
import com.yunyao.framework.dto.soSupply.SosupplySaveDto;
import com.yunyao.framework.service.SoSupplyService;
import com.yunyao.framework.vo.sosyupply.SoSupplyVO;
import com.yunyao.framework.vo.sosyupply.SoSupplinfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SoSupplyServiceIml implements SoSupplyService {
    @Autowired
    private IBamuSoSupplyService iBamuSoSupplyService;
    @Autowired
    private IBamuPurchaseApplyService iBamuPurchaseApplyService;
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;

    @Override
    public YResult<PageResult<SoSupplyVO>> pageList(SoSupplyDto soSupplyDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuSoSupply> queryWrapper = new LambdaQueryWrapper<BamuSoSupply>()
                .eq(StringUtils.isNotEmpty(BaseContext.getUserInfo().getTenantId()), BamuSoSupply::getTenantId, BaseContext.getUserInfo().getTenantId())
                .eq(StringUtils.isNotEmpty(soSupplyDto.getApplyId()), BamuSoSupply::getApplyId, soSupplyDto.getApplyId())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSoSupply::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuSoSupply::getSupplierId, BaseContext.getSupplierList())
                .like(StringUtils.isNotBlank(soSupplyDto.getOrderSn()), BamuSoSupply::getOrderSn, soSupplyDto.getOrderSn())
                .like(StringUtils.isNotBlank(soSupplyDto.getOrderName()), BamuSoSupply::getOrderName, soSupplyDto.getOrderName())
                .eq(StringUtils.isNotBlank(soSupplyDto.getProjectId()), BamuSoSupply::getProjectId, soSupplyDto.getProjectId())
                .like(StringUtils.isNotBlank(soSupplyDto.getProjectName()), BamuSoSupply::getProjectName, soSupplyDto.getProjectName())
                .eq(StringUtils.isNotBlank(soSupplyDto.getContractId()), BamuSoSupply::getContractId, soSupplyDto.getContractId())
                .like(StringUtils.isNotBlank(soSupplyDto.getContractName()), BamuSoSupply::getContractName, soSupplyDto.getContractName())
                .eq(StringUtils.isNotBlank(soSupplyDto.getReconciliationStatus()), BamuSoSupply::getReconciliationStatus, soSupplyDto.getReconciliationStatus())
                .eq(soSupplyDto.getSupplyStatus() != null, BamuSoSupply::getSupplyStatus, soSupplyDto.getSupplyStatus())
                .eq(BamuSoSupply::getIsDeleted, 0)
                .orderByDesc(BamuSoSupply::getCreatedAt);
        // 分页查询
        IPage<BamuSoSupply> soSupplyPage = new Page<>(soSupplyDto.getPageIndex(), soSupplyDto.getPageSize());
        soSupplyPage = iBamuSoSupplyService.page(soSupplyPage, queryWrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(soSupplyPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<SoSupplyVO> soSupplyVOList = daoToVoList(soSupplyPage.getRecords());
        //项目对账-新增编辑:选择验收清单过滤已选择数据
        if (CollectionUtils.isNotEmpty(soSupplyDto.getSoSupplyIds())) {
            List<SoSupplyVO> vos = filterSelect(soSupplyVOList, soSupplyDto.getSoSupplyIds());
            return YResult.success(new PageResult<>(vos, soSupplyPage.getCurrent(), soSupplyPage.getSize(), soSupplyPage.getPages(), soSupplyPage.getTotal()));
        }
        // 返回分页结果
        return YResult.success(new PageResult<>(soSupplyVOList, soSupplyPage.getCurrent(), soSupplyPage.getSize(), soSupplyPage.getPages(), soSupplyPage.getTotal()));
    }



    /**
     * 根据已选中的结算单ID过滤掉
     *
     * @param voList      列表
     * @param soSupplyIds 已选择
     */
    private List<SoSupplyVO> filterSelect(List<SoSupplyVO> voList, List<String> soSupplyIds) {
        /*if (CollectionUtils.isEmpty(soSupplyIds) && StringUtils.isNotBlank(contractId)) {
            List<BamuSoSupply> soSupplies = iBamuSoSupplyService.lambdaQuery()
                    .eq(BamuSoSupply::getContractId, contractId)
                    .eq(BamuSoSupply::getIsDeleted, DataDeletedStatus.NO.getType())
                    .list();
            if (CollectionUtils.isNotEmpty(soSupplies)) {
                List<String> supplyIds = soSupplies.stream().map(BamuSoSupply::getId).toList();
                return voList.stream().filter(s -> !supplyIds.contains(s.getId())).collect(Collectors.toList());
            }
        }*/
        return voList.stream().filter(s -> !soSupplyIds.contains(s.getId())).collect(Collectors.toList());
    }

    private List<SoSupplyVO> daoToVoList(List<BamuSoSupply> records) {
        return records.stream().map(this::daoToVo).collect(Collectors.toList());
    }

    private SoSupplyVO daoToVo(BamuSoSupply bamuSoSupply) {
        SoSupplyVO soSupplyVO = new SoSupplyVO();
        BeanUtils.copyProperties(bamuSoSupply, soSupplyVO);
        return soSupplyVO;
    }

    @Override
    public YResult<SoSupplinfoVO> getSoSupplyById(String id) {
        BamuSoSupply bamuSoSupply = iBamuSoSupplyService.getById(id);
        // 处理查询结果
        if (Objects.isNull(bamuSoSupply)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        BamuPurchaseApply bamuPurchaseApply = iBamuPurchaseApplyService.getById(bamuSoSupply.getApplyId());
        SoSupplinfoVO soSupplinfoVO = daoToInfoVO(bamuSoSupply);
        soSupplinfoVO.setCopperPrice(bamuPurchaseApply.getCopperPrice());
        soSupplinfoVO.setCopperDate(bamuPurchaseApply.getCopperDate());
        soSupplinfoVO.setCopperUpdatePersonName(bamuPurchaseApply.getCopperUpdatePersonName());
        soSupplinfoVO.setCopperUpdatePersonId(bamuPurchaseApply.getCopperUpdatePersonId());
        soSupplinfoVO.setAttachFiles(bamuPurchaseApply.getAttachFiles());
        List<BamuAuditConfirmHistory> confirmHistory = iBamuAuditConfirmHistoryService.getListByBizIdAndType(bamuPurchaseApply.getId(), null, false);
        if (CollectionUtils.isNotEmpty(confirmHistory)) {
            soSupplinfoVO.setSupplierFiles(confirmHistory.get(0).getFile());
        }
        return YResult.success(soSupplinfoVO);
    }

    @Override
    public List<SoSupplinfoVO> getSupplyByapplyId(String id) {
        LambdaQueryWrapper<BamuSoSupply> wrapper = new LambdaQueryWrapper<BamuSoSupply>()
                .eq(BamuSoSupply::getApplyId, Long.parseLong(id));
        BamuSoSupply bamuSoSupply = iBamuSoSupplyService.getOne(wrapper);

        // 处理查询结果
        if (Objects.isNull(bamuSoSupply)) {
            return Collections.emptyList(); // 返回空列表而不是进行类型转换
        }
        return Collections.singletonList(daoToInfoVO1(bamuSoSupply)); // 返回包含单个元素的列表
    }

    @Override
    public YResult<String> saveInfo(SosupplySaveDto saveDto) {
        BamuSoSupply bamuSoSupply = new BamuSoSupply();
        BeanUtils.copyProperties(saveDto, bamuSoSupply);
        bamuSoSupply.setCreatedAt(saveDto.getCreatedAt());
        bamuSoSupply.setShipmentAt(saveDto.getShipmentAt());
        iBamuSoSupplyService.saveOrUpdate(bamuSoSupply);
        return YResult.success(bamuSoSupply.getId());
    }


    private SoSupplinfoVO daoToInfoVO(BamuSoSupply bamuSoSupply) {
        SoSupplinfoVO soSupplinfoVO = new SoSupplinfoVO();
        BeanUtils.copyProperties(bamuSoSupply, soSupplinfoVO);
        return soSupplinfoVO;
    }

    private SoSupplinfoVO daoToInfoVO1(BamuSoSupply bamuSoSupply) {
        SoSupplinfoVO soSupplinfoVO = new SoSupplinfoVO();
        BeanUtils.copyProperties(bamuSoSupply, soSupplinfoVO);
        return soSupplinfoVO;
    }

    @Override
    public List<SupplyExcelDto> export(SoSupplyDto soSupplyDto) {
        LambdaQueryWrapper<BamuSoSupply> queryWrapper = new LambdaQueryWrapper<BamuSoSupply>()
                .eq(StringUtils.isNotEmpty(BaseContext.getUserInfo().getTenantId()),BamuSoSupply::getTenantId, BaseContext.getUserInfo().getTenantId())
                .eq(StringUtils.isNotEmpty(soSupplyDto.getApplyId()), BamuSoSupply::getApplyId, soSupplyDto.getApplyId())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSoSupply::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuSoSupply::getSupplierId, BaseContext.getSupplierList())
                .like(StringUtils.isNotBlank(soSupplyDto.getOrderSn()), BamuSoSupply::getOrderSn, soSupplyDto.getOrderSn())
                .like(StringUtils.isNotBlank(soSupplyDto.getOrderName()), BamuSoSupply::getOrderName, soSupplyDto.getOrderName())
                .eq(StringUtils.isNotBlank(soSupplyDto.getProjectId()), BamuSoSupply::getProjectId, soSupplyDto.getProjectId())
                .like(StringUtils.isNotBlank(soSupplyDto.getProjectName()), BamuSoSupply::getProjectName, soSupplyDto.getProjectName())
                .eq(StringUtils.isNotBlank(soSupplyDto.getContractId()), BamuSoSupply::getContractId, soSupplyDto.getContractId())
                .like(StringUtils.isNotBlank(soSupplyDto.getContractName()), BamuSoSupply::getContractName, soSupplyDto.getContractName())
                .eq(StringUtils.isNotBlank(soSupplyDto.getReconciliationStatus()), BamuSoSupply::getReconciliationStatus, soSupplyDto.getReconciliationStatus())
                .eq(soSupplyDto.getSupplyStatus() != null, BamuSoSupply::getSupplyStatus, soSupplyDto.getSupplyStatus())
                .eq(BamuSoSupply::getIsDeleted, 0)
                .orderByDesc(BamuSoSupply::getCreatedAt);
        List<BamuSoSupply> contractMaterialList  = iBamuSoSupplyService.list(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractMaterialList)){
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private SupplyExcelDto convertToExcelDto(BamuSoSupply bamuSoSupply){
        SupplyExcelDto dto = new SupplyExcelDto();
        BeanUtils.copyProperties(bamuSoSupply, dto);
        dto.setId(bamuSoSupply.getId());
        return dto;
    }

}
